#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import time
import logging
import traceback
from HTMLParser import HTMLParser
from datetime import datetime
from random import shuffle
from re import sub
from sys import stderr
from traceback import print_exc

# -*- coding: utf-8 -*-
from flask import render_template, url_for, redirect, request, flash, session, abort, Blueprint
from flask_cache import Cache
from werkzeug.utils import secure_filename
from werkzeug.contrib.atom import AtomFeed

from models.model import Category, Post, Tag, Comment, pageby, db
# from myapp import app
from config import PER_PAGE as per_page

# cache = Cache(app, config={'CACHE_TYPE': 'simple'})
# app.config.from_object('config')
# per_page = app.config['PER_PAGE']
common = Blueprint('common', __name__, url_prefix="/common")

log = logging.getLogger(__file__)

class PostFeed(AtomFeed):

    def add_post(self, post):
        self.add(post.post_title,
                 '',
                 content_type="html",
                 author=u'dan',
                 url=post.url,
                 updated=datetime.now(),
                 published=post.post_create_time)

def is_chinese(text):
    if text:
        for uchar in text:
            if uchar >= u'\u4e00' and uchar <= u'\u9fa5':
                return True
    return False


@common.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404


@common.route('/error/404')
def error_404():
    return render_template('404.html'), 404


@common.route('/about')
# @cache.cached(timeout=300)
def about():
    categorys = Category.query.getall()
    hot = Post.query.hottest()[:20]
    new = Post.query.newpost()[:20]

    tag = Tag.query.getall()
    shuffle(tag)
    tag = tag[:20]

    comments = Comment.query.newcomment()[:20]

    return render_template('/about.html',
                           categorys=categorys,
                           hotarticles=hot,
                           newpost=new,
                           tags=tag,
                           comments=comments)

@common.route('/search')
@common.route('/search/page/<int:pageid>')
# @cache.cached(timeout=240)
def search(pageid=1):
    categorys = Category.query.getall()
    hot = Post.query.hottest()[:20]
    new = Post.query.newpost()[:20]
    tag = Tag.query.getall()
    shuffle(tag)
    tag = tag[:20]
    comments = Comment.query.newcomment()[:20]

    searchword = request.args.get('s', '')
    if not searchword:
        return redirect(url_for('error_404'))

    searchresult = Post.query.search(searchword)

    p = pageby(searchresult, pageid, per_page, Post.post_create_time.desc())

    articles = p.items
    if not p.total:
        pagination = [0]
    elif p.total % per_page:
        pagination = range(1, p.total / per_page + 2)
    else:
        pagination = range(1, p.total / per_page + 1)

    return render_template('/search.html',
                           key=searchword,
                           categorys=categorys,
                           articles=articles,
                           hotarticles=hot,
                           newpost=new,
                           tags=tag,
                           comments=comments,
                           pageid=pageid,
                           pagination=pagination[pageid - 1:pageid + 10],
                           last_page=pagination[-1]
                           )

@common.route('/error')
def error(content='404'):
    return render_template('/error.html', content=content)

